﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using Lavka.Core;
using Lavka.Mailers;
using Lavka.Models;
using Mvc.Mailer;

namespace Lavka.Controllers
{ 
    public class OrdersController : Controller
    {
        private LavkaDbEntities context = new LavkaDbEntities();

        //
        // GET: /Orders/
        [Authorize(Roles = "Administrators")]
        public ViewResult Index()
        {
            var orders = context.Orders.Include("Customers");
            return View(orders.ToList());
        }

        //
        // GET: /Orders/Details/5
        [Authorize(Roles = "Administrators")]
        public ViewResult Details(int id)
        {
            Orders orders = context.Orders.Single(o => o.OrderId == id);
            return View(orders);
        }

        //
        // GET: /Orders/Create
        [HttpGet]
        public ActionResult Create()
        {
            ViewBag.CustomerId = "-1";
            return View();
        }

        public ActionResult Create(int productId)
        {
            ViewBag.CustomerId = "-1";
            return View();
        } 
        //
        // POST: /Orders/Create

        [HttpPost]
        public ActionResult Create(Orders orders, FormCollection formCollection)
        {
            Customers customer = null;
            var key = Request.Form["CustomerKey"];
            {
                if(!string.IsNullOrEmpty(key))
                {
                    customer = CustomersHelper.UpdateCustomer(Request.Form["CustomerId"], Request.Form["Name"], Request.Form["Phone"],
                        Request.Form["Email"], Request.Form["DeliveryAddress"], context);
                    orders.OrderByKey = true;
                }
                else
                {
                    customer = CustomersHelper.CreateCustomer(Request.Form["Name"], Request.Form["Phone"], 
                        Request.Form["Email"], Request.Form["DeliveryAddress"], context);
                    orders.OrderByKey = false;
                }
            }

            orders.CustomerId = customer.CustomerId;
            orders.OrderKey = OrdersHelper.GenerateOrderKey(customer.CustomerId);

            if (ModelState.IsValid)
            {
                context.Orders.AddObject(orders);
                int rowsProcessed = context.SaveChanges();
                if (rowsProcessed > 0)
                {
                    foreach (Products product in CartHelper.Cart)
                    {
                        OrderedProducts op = new OrderedProducts()
                                                 {
                                                     OrderId = orders.OrderId,
                                                     ProductId = product.ProductId,
                                                     ItemPrice = (decimal)product.Price,
                                                     Number =
                                                         Convert.ToInt32(
                                                             Request.Form["num_" + product.ProductId])
                                                 };
                        context.OrderedProducts.AddObject(op);
                        int opProcessed = context.SaveChanges();
                        if (opProcessed == 0)
                        {
                            return PartialView("Error");
                        }
                    }

                    try
                    {
                        var mailer = new MailSender();
                        MailMessage message = mailer.UserMessage(orders.Customers.Email, orders);
                        message.Send(SettingsManager.GetSmtpClient());
                    }
                    catch (Exception ex)
                    {
                    }

                    CartHelper.ClearCart(context);
                    return View("OrderComplete");
                }
                else
                {
                    return PartialView("Error");
                }
            }

            ViewBag.CustomerId = new SelectList(context.Customers, "CustomerId", "Name", orders.CustomerId);
            return View(orders);
        }
        public ActionResult DeleteItem(int id)
        {
            CartHelper.DeleteItem(id);
            Response.Redirect(Request.UrlReferrer.ToString());
            return null;
        }
        //
        // GET: /Orders/Edit/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(int id)
        {
            Orders orders = context.Orders.Single(o => o.OrderId == id);
            ViewBag.CustomerId = new SelectList(context.Customers, "CustomerId", "Name", orders.CustomerId);
            return View(orders);
        }

        //
        // POST: /Orders/Edit/5

        [HttpPost]
        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(Orders orders)
        {
            if (ModelState.IsValid)
            {
                context.Orders.Attach(orders);
                context.ObjectStateManager.ChangeObjectState(orders, EntityState.Modified);
                context.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CustomerId = new SelectList(context.Customers, "CustomerId", "Name", orders.CustomerId);
            return View(orders);
        }

        //
        // GET: /Orders/Delete/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id)
        {
            Orders orders = context.Orders.Single(o => o.OrderId == id);
            return View(orders);
        }

        //
        // POST: /Orders/Delete/5
        [Authorize(Roles = "Administrators")]
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Orders orders = context.Orders.Single(o => o.OrderId == id);
            context.Orders.DeleteObject(orders);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            context.Dispose();
            base.Dispose(disposing);
        }

        [HttpPost]
        public string RecaluclateSumPrice(string itemNums)
        {
            var separator = new []{","};
            string[] items = itemNums.Split(separator, StringSplitOptions.RemoveEmptyEntries);

            return "<div id=\"SumPrice\">"+ CartHelper.RecalucatePrice(items, context) + "грн. </div>";
        }

        [HttpPost]
        public ActionResult GetCustomerDetailsByKey(string customerKey)
        {
            Customers c = CustomersHelper.GetCustomerByOrderKey(customerKey, context);
            if(c != null)
            {
                ViewData["CustomerKey"] = customerKey;
            }
            else
            {
                c = new Customers();
            }
            return PartialView("CustomerDetails", c);
        }
    }
}